//对象数组的深拷贝
export function deepCopy(source) {
  var sourceCopy = source instanceof Array ? [] : {};
  for (var item in source) {
    sourceCopy[item] = typeof source[item] === 'object' && source[item] != null ? deepCopy(source[item]) : source[item];
  }
  return sourceCopy;
}

// 获取数组中所有节点的id
export function getArrChildIds(arr, id = 'id', child = 'children') {
  let temp = [];
  let forFn = (list) => {
    for (let item of list) {
      temp.push(item[id]);
      if (item[child]) {
        forFn(item[child]);
      }
    }
  };
  forFn(arr);
  return temp;
}

/* 根据url下载图片 */
export function downloadByBlobImg(url, name) {
  let image = new Image()
  image.setAttribute('crossOrigin', 'anonymous')
  image.src = url
  image.onload = () => {
    let canvas = document.createElement('canvas')
    canvas.width = image.width
    canvas.height = image.height
    let ctx = canvas.getContext('2d')
    ctx.drawImage(image, 0, 0, image.width, image.height)
    canvas.toBlob((blob) => {
      let url = URL.createObjectURL(blob);
      download(url, name);
      // 用完释放URL对象
      URL.revokeObjectURL(url);
    },
      'image/jpeg'
    )
  }
  function download(href, name) {
    let eleLink = document.createElement('a');
    eleLink.download = name || '';
    eleLink.href = href;
    eleLink.click();
    eleLink.remove();
  }
};

// 格式化日期时间
export function formatDateTime(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
};

function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

export function setSessionStorage(key, value) {
  return sessionStorage.setItem(key, value);
}
export function getSessionStorage(key) {
  return sessionStorage.getItem(key);
}
export function rmSessionStorage(key) {
  return sessionStorage.removeItem(key);
}

// 指定长度和基数
export function generateUUID(len, radix) {
  var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  var uuid = [],
      i;
  radix = radix || chars.length;

  if (len) {
      // Compact form
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
  } else {
      // rfc4122, version 4 form
      var r;

      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
              r = 0 | Math.random() * 16;
              uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
          }
      }
  }
  return uuid.join('');
}



export default {
  install(Vue) {
    Vue.prototype.$fn = {
      deepCopy,
      getArrChildIds,
      setSessionStorage,
      getSessionStorage,
      rmSessionStorage,
      downloadByBlobImg,
      formatDateTime,
      generateUUID
    };
  }
}